package com.lihan.GetSeatInLib.Interceptors;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lihan.GetSeatInLib.Exceptions.UnableJWTexception;
import com.lihan.GetSeatInLib.Service.JwtService;
import com.lihan.GetSeatInLib.Tools.PassTokenAnnoation;

@Component
public class JwtInterceptor implements HandlerInterceptor{
	
	@Autowired
	private JwtService jwtService;
	
	private static String Auth = "Authorize";
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		
//		if (!(handler instanceof HandlerMethod)) {
//            return true;
//        }
		System.out.println("wdnmd");
		HandlerMethod handlerMehod = (HandlerMethod)handler;
		
		Method method = handlerMehod.getMethod();
		
		//如果是打了无须验证的注解的方法就直接放行
		if(method.isAnnotationPresent(PassTokenAnnoation.class)) {
			PassTokenAnnoation pass = method.getAnnotation(PassTokenAnnoation.class);
			if(pass.PassIt())
				return true;
		}
		
		String token = request.getHeader(Auth);
		System.out.println("-----token" + token);
		String username = request.getHeader("username");
		System.out.println("-----token" + username);
		
		if(StringUtils.isEmpty(token)) {
			System.out.println("这里显然是进token判断了");
			throw new UnableJWTexception(400, "没有携带JWT或jwt信息错误");
		}
		
		if(StringUtils.isEmpty(username))
			throw new UnableJWTexception(400, "没有携带JWT或jwt信息错误");	
		//验证JWT
		if(jwtService.verifierToken(token, username))
			return true;
		else {
			throw new UnableJWTexception(400, "没有携带JWT或JWT信息错误");
			
		}
	}
	
	
	
	
	
	
	
	
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

}
